import streamlit as st
from datetime import datetime

class LogsView:
    """日志视图类"""
    
    def __init__(self):
        pass
    
    def render(self):
        """渲染日志查看页面 - 与app_ui.py完全一致"""
        st.markdown("<h1 class='main-header'>系统日志</h1>", unsafe_allow_html=True)
        
        # 日志控制按钮
        col1, col2, col3 = st.columns([1, 1, 1])
        with col1:
            refresh_button = st.button("刷新日志", use_container_width=True)
        with col2:
            clear_button = st.button("清空日志", use_container_width=True)
        with col3:
            export_button = st.button("导出", use_container_width=True)
        
        # 处理按钮事件
        if refresh_button:
            st.rerun()
        
        if clear_button:
            st.session_state.log_messages = []
            st.success("✅ 日志已清空")
            st.rerun()
        
        if export_button:
            if st.session_state.log_messages:
                # 创建日志文件内容
                log_content = "\n".join(st.session_state.log_messages)
                
                # 创建下载按钮
                st.download_button(
                    label="下载日志文件",
                    data=log_content,
                    file_name=f"emlaidata_logs_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt",
                    mime="text/plain",
                    use_container_width=True
                )
            else:
                st.warning("⚠️ 暂无日志可导出")
        
        # 显示日志
        if st.session_state.log_messages:
            log_text = "\n".join(st.session_state.log_messages)
            st.text_area("实时日志", log_text, height=500, key="log_display")
            
            # 显示日志统计
            st.info(f"📊 当前显示 {len(st.session_state.log_messages)} 条日志记录")
        else:
            st.info("📝 暂无处理日志")